local addonName, IWonew = ...

SellCraftItemsClass = {}
SellCraftItemsClass.__index = SellCraftItemsClass

function SellCraftItemsClass:new()
  local instance = setmetatable({}, SellCraftItemsClass)
  instance.items = {}
  instance.scanTicker = nil
	return instance
end

function SellCraftItemsClass:registerEvents()
  local f = CreateFrame("Frame")
  -- f:RegisterEvent("ITEM_SEARCH_RESULTS_UPDATED")
  f:RegisterEvent("COMMODITY_SEARCH_RESULTS_UPDATED")
  local rootSelf = self
  function f:OnEvent(event, ...)
    rootSelf[event](rootSelf, event, ...)
  end
  f:SetScript("OnEvent", f.OnEvent)
end

function SellCraftItemsClass:getItemInfo(itemID)
  local info = nil
  for i = 1, #self.items do
    if self.items[i].itemID == itemID then
      info = self.items[i]
    end
  end
  return info
end

function SellCraftItemsClass:removeItem(itemID)
  local newList = {}
  for i = 1, #self.items do
    if self.items[i].itemID ~= itemID then
      table.insert(newList, self.items[i])
    end
  end
  return newList
end

function SellCraftItemsClass:COMMODITY_SEARCH_RESULTS_UPDATED(event, itemID)
  local itemInfo = self:getItemInfo(itemID)
  if not itemInfo then return end
  local result = C_AuctionHouse.GetCommoditySearchResultInfo(itemID, 1)

  if self["frame_"..itemID] ~= nil then
    self["frame_"..itemID]:UnregisterAllEvents()
    self["frame_"..itemID]:ClearAllPoints()
    self["frame_"..itemID]:Hide()
    self["frame_"..itemID] = nil  -- 将框架设置为 nil，允许垃圾回收器清理内存
  end
  if result and not result.containsOwnerItem then
    print("result " .. IWonew.getCurrentTimeStr(), result.unitPrice)
    local itemSlot = IWonew.GetItemSlot(itemID)
    if itemSlot == nil then
      self.items = self:removeItem(itemID)
      return
    end
    local unitPrice = result.unitPrice
    if unitPrice < itemInfo.minPrice then return end
    
    
    local frame = IWonew.CreateTextFrame(80, "卖A", itemInfo.xPos, 0)
    self["frame_"..itemID] = frame
    frame:SetScript("OnClick", function()
      -- 取消事件注册，移除脚本，清除位置，隐藏框架
      frame:UnregisterAllEvents()
      frame:ClearAllPoints()
      frame:Hide()
      frame = nil  -- 将框架设置为 nil，允许垃圾回收器清理内存
      self["frame_"..itemID] = nil
      local quality = math.min(itemSlot.stackCount, math.random(1, 10) % 3 + 2)
      -- 晶脉辉煌每次上架数量为1，
      if itemID == 223692 then
        quality = 1
      end
      -- 诅咒急速每次上架数量为1
      if itemID == 223790 then
        quality = 1
      end
      -- -- needsConfirmation = C_AuctionHouse.PostItem(item, duration, quantity [, bid [, buyout]])
      C_AuctionHouse.PostCommodity(ItemLocation:CreateFromBagAndSlot(itemSlot.bagID, itemSlot.slotID), 1, quality, unitPrice)
      print("开始拍卖 " .. IWonew.getCurrentTimeStr() .. " unitPrice=" .. result.unitPrice .. " quantity=" .. quality)
      -- print("needsConfirmationneedsConfirmationneedsConfirmation", needsConfirmation)
    end)
  end
end



function SellCraftItemsClass:Scan()
  if self.scanIdx == nil then
    self.scanIdx = 0
  end
  local sorts = {
    {sortOrder = Enum.AuctionHouseSortOrder.Price, reverseSort = false},
  }
  if #self.items == 0 then
    self:stop()
    print("Sale Done!!")
    return
  end
  local itemInfo = self.items[self.scanIdx % #self.items + 1]
  if itemInfo == nil then
    return
  end
  local itemKey = {itemID = itemInfo.itemID}
  C_AuctionHouse.SendSearchQuery(itemKey, sorts, true)
  self.scanIdx = self.scanIdx + 1
end

function SellCraftItemsClass:start(items)
  self:stop()
  local formatItems = {}
  for i = 1, #items do
    local cloneItem = IWonew.deepCopy(items[i])
    cloneItem.xPos = 80 * i
    table.insert(formatItems, cloneItem)
  end
  self.items = formatItems
  local rootSelf = self
  self.scanTicker = C_Timer.NewTicker(2, function()
    rootSelf:Scan()
  end)
end

function SellCraftItemsClass:stop()
  if self.scanTicker ~= nil then
    self.scanTicker:Cancel()
  end
end

function SellCraftItemsClass:debug()
  local sorts = {
    {sortOrder = Enum.AuctionHouseSortOrder.Price, reverseSort = false},
  }
  local itemKey = {itemID = 223692}
  C_AuctionHouse.SendSearchQuery(itemKey, sorts, true)
end

function SellCraftItemsClass:postItem(itemID, ...)
end

local SellCraftItemsClass_instance = nil
function CreateSellCraftItemsClassInstance()
  if SellCraftItemsClass_instance == nil then
    SellCraftItemsClass_instance = SellCraftItemsClass:new()
    SellCraftItemsClass_instance:registerEvents()
  end
  return SellCraftItemsClass_instance
end
-- /dump StartSellCratingItems({{itemID = 223692, minPrice = 1600 * 10000}})
-- /dump StartSellCratingItems({{itemID = 223692, minPrice = 1600 * 10000}, {itemID = 222428, minPrice = 600 * 10000}})
-- /dump StartSellCratingItems({223692, 222428, 223790})
function StartSellCratingItems(items)
  local instance = CreateSellCraftItemsClassInstance()
  
  instance:start(items)
end

function StopSellCratingItems()
  local instance = CreateSellCraftItemsClassInstance()
  instance:stop()
end
-- /dump DebugSellCratingItems()
function DebugSellCratingItems()
  C_AuctionHouse.PostCommodity(ItemLocation:CreateFromBagAndSlot(0, 1), 1, 1, 1655.17 * 10000)
  -- local instance = CreateSellCraftItemsClassInstance()
  -- instance:debug()
end
